package com.open.capacity.reimburse.service.impl;

import com.open.capacity.model.system.LoginAppUser;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.dao.*;
import com.open.capacity.reimburse.entity.*;
import com.open.capacity.reimburse.service.HtAgreementService;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.reimburse.exception.BusinessException;
import com.open.capacity.user.model.SysFile;
import com.open.capacity.user.service.SysAreaService;
import com.open.capacity.user.service.SysFileService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.SysUserUtil;
import com.open.capacity.workflow.service.WFProcessinstanceService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.service.BillRepair2Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;


@Service
public class BillRepair2ServiceImpl implements BillRepair2Service {

    @Autowired
    private BillRepair2Dao billDao;

    @Autowired
    private BillRepair2ContractDao contractDao;

    @Autowired
    private BillRepair2CostDao costDao;

    @Autowired
    private SysUserService userService;

    @Autowired
    private SysAreaService areaService;

    @Autowired
    private SysFileService fileService;

    @Autowired
    private HtAgreementService htAgreementService;

    @Autowired
    private WFProcessinstanceService processinstanceService;

    @Override
    public int verifyBill(BillRepair2 bill) {
        String errorMsg = verify(bill);
        if (StringUtils.isNotEmpty(errorMsg)) {
            throw new BusinessException(errorMsg);
        }
        return 1;
    }

    /**
     * 添加
     *
     * @param bill
     */
    @Transactional(rollbackFor = Exception.class)
    public int save(BillRepair2 bill, Integer force) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();

        if (force != 1) {
            //规则校验
            String errorMsg = verify(bill);
            if (StringUtils.isNotEmpty(errorMsg)) {
                throw new BusinessException(errorMsg);
            }
        }

        bill.setStatus(1);
        bill.setCreateTime(new Date());
        bill.setCreateUserid(loginUser.getId());
        bill.setCreateUsername(loginUser.getRealName());

        SysUser user = userService.findById(bill.getUserid());
        Assert.notNull(user, "找不到报销人信息");
        bill.setUsername(user.getRealName());

        bill.getContractList().forEach(item -> {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setRefId(bill.getId());
            contractDao.save(item);

            HtAgreement agreement = new HtAgreement();
            agreement.setCreateTime(new Date());
            agreement.setCreateUsername(loginUser.getRealName());
            agreement.setCreateUserid(loginUser.getId());
            agreement.setNumber(item.getNumber());
            agreement.setTitle(item.getTitle());
            agreement.setFiles(item.getFiles());
            agreement.setMoney(item.getMoney());
            agreement.setStatus(1);
            agreement.setOtherUnits("setOtherUnits"); //TODO
            agreement.setSummary("setSummary");//TODO
            agreement.setCategory("1"); //TODO
            htAgreementService.save(agreement);
        });

        BigDecimal cost = BigDecimal.ZERO;
        for (BillRepair2Cost item : bill.getCostList()) {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setRefId(bill.getId());
            if (item.getMoney() != null) {
                cost = cost.add(item.getMoney());
            }
            costDao.save(item);
        }
        bill.setCost(cost);
        int count = billDao.save(bill);
        return count;
    }

    //数据校验
    public String verify(BillRepair2 bill) {
        String errorMsg = "";
        String userId = bill.getUserid();
        Date startTime = bill.getStartTime();//开始时间
        Date endTime = bill.getEndTime();//结束时间

        for (BillRepair2Cost item : bill.getCostList()) {
            switch (item.getItemCode()) {
                case "1": //住宿费校验
                    // errorMsg += stdHotelService.verify(userId, followUserids, item.getPersons(), destination, startTime, endTime, item.getMoney());
                    break;
                case "2": //机票费
                    //  errorMsg += stdTrafficService.verify(userId, followUserids, TrafficTypes.PLANE, item.getMoney());
                    break;
                case "4": //伙食补贴校验
                    //  errorMsg += stdMealAllowanceService.verify(userId, followUserids, item.getPersons(), destination, startTime, endTime, item.getMoney());
                    break;
                case "5": //市内交通补贴校验
                    //   errorMsg += stdTrafficAllowanceService.verify(userId, followUserids, item.getPersons(), destination, startTime, endTime, item.getMoney());
                    break;
            }
        }

        return errorMsg;
    }


    /**
     * 修改
     *
     * @param bill
     */
    @Transactional(rollbackFor = Exception.class)
    public int update(BillRepair2 bill, Integer force) {
        LoginAppUser loginUser = SysUserUtil.getLoginAppUser();

        if (force != 1) {
            //规则校验
            String errorMsg = verify(bill);
            if (StringUtils.isNotEmpty(errorMsg)) {
                throw new BusinessException(errorMsg);
            }
        }

        bill.setStatus(1);
        //bill.setCreateTime(new Date());
        //bill.setCreateUserid(loginUser.getId());
        //bill.setCreateUsername(loginUser.getRealName());

        SysUser user = userService.findById(bill.getUserid());
        Assert.notNull(user, "找不到报销人信息");
        bill.setUsername(user.getRealName());

        //合同
        bill.getContractList().forEach(item -> {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setRefId(bill.getId());
            contractDao.save(item);

            HtAgreement agreement = new HtAgreement();
            agreement.setCreateTime(new Date());
            agreement.setCreateUsername(loginUser.getRealName());
            agreement.setCreateUserid(loginUser.getId());
            agreement.setNumber(item.getNumber());
            agreement.setTitle(item.getTitle());
            agreement.setFiles(item.getFiles());
            agreement.setMoney(item.getMoney());
            agreement.setStatus(1);
            agreement.setOtherUnits("setOtherUnits"); //TODO
            agreement.setSummary("setSummary");//TODO
            agreement.setCategory("1"); //TODO
            htAgreementService.save(agreement);
        });

        BigDecimal cost = BigDecimal.ZERO;
        costDao.deleteByRefId(bill.getId());
        for (BillRepair2Cost item : bill.getCostList()) {
            item.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            item.setRefId(bill.getId());
            if (item.getMoney() != null) {
                cost = cost.add(item.getMoney());
            }
            costDao.save(item);
        }
        bill.setCost(cost);
        int count = billDao.update(bill);
        return count;
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return billDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public BillRepair2 findById(String id) {
        BillRepair2 bill = billDao.findById(id);
        if (bill != null) {
            bill.setCostList(costDao.findByRefId(id));
            List<BillRepair2Contract> contractList = contractDao.findByRefId(id);
            contractList.forEach(item -> {
                List<SysFile> fileList = fileService.findByFolderId(item.getFiles());
                String fileName = "";
                for (SysFile f : fileList) {
                    if (StringUtil.isEmpty(fileName)) {
                        fileName += f.getName();
                    } else {
                        fileName += "," + f.getName();
                    }
                    item.setFileNames(fileName);
                }
            });

            bill.setContractList(contractList);
            bill.setProcessCode(processinstanceService.findById(id).getCode());
        }
        return bill;
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<BillRepair2> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<BillRepair2> list = billDao.findAll(params);
        PageInfo<BillRepair2> pageInfo = new PageInfo(list);

        return PageResult.<BillRepair2>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<BillRepair2> findAll(Map<String, Object> params) {
        return billDao.findAll(params);
    }

}
